package com.kantboot.system.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.kantboot.functional.common.service.ICommonKantbootRsaService;
import com.kantboot.system.user.dao.repository.entity.SysUserRepository;
import com.kantboot.system.user.dao.repository.vo.SysUserVOOfSelfRepository;
import com.kantboot.system.user.domain.dto.InitSelfInfoDTO;
import com.kantboot.system.user.domain.entity.SysUser;
import com.kantboot.system.user.domain.vo.SysUserOfSelfInfoVO;
import com.kantboot.system.user.domain.vo.SysUserOfSelfVO;
import com.kantboot.system.user.exception.SystemUserException;
import com.kantboot.system.user.service.ISysTokenService;
import com.kantboot.system.user.service.ISysUserRoleService;
import com.kantboot.system.user.service.IUserSelfService;
import com.kantboot.util.common.http.HttpRequestHeaderUtil;
import com.kantboot.util.common.password.KantbootPassword;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserSelfServiceImpl implements IUserSelfService {

    @Resource
    private SysUserRepository userRepository;

    @Resource
    private SysUserVOOfSelfRepository userVOOfSelfShowRepository;

    @Resource
    private HttpRequestHeaderUtil httpRequestHeaderUtil;

    @Resource
    private ISysTokenService tokenService;

    @Resource
    private KantbootPassword kantbootPassword;

    @Resource
    private ICommonKantbootRsaService kantbootRsaService;


    @Override
    public SysUserOfSelfVO getSelf() {
        Long selfId = getSelfId();
        return userVOOfSelfShowRepository.findById(selfId).orElseThrow(
                // 如果没有找到用户，抛出未登录异常
                () -> SystemUserException.NOT_LOGIN
        );
    }

    @Override
    public Long getSelfId() {
        String token = httpRequestHeaderUtil.getToken();
        Long userIdByToken = tokenService.getUserIdByToken(token);
        if (userIdByToken == null) {
            // 如果没有找到用户，抛出未登录异常
            throw SystemUserException.NOT_LOGIN;
        }
        return userIdByToken;
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        Long selfId = getSelfId();
        // 数据库中的密码
        String passwordById = userRepository.findPasswordById(selfId);
        if(!kantbootPassword.matches(oldPassword, passwordById)){
            // 如果原密码不正确，抛出原密码错误异常
            throw SystemUserException.OLD_PASSWORD_ERROR;
        }
        // 修改密码
        userRepository.updatePasswordById(selfId, kantbootPassword.encode(newPassword));
    }

    @Override
    public void changePasswordWithSecurity(String oldPassword, String newPassword) {
        String oldPasswordDecrypt = kantbootRsaService.decrypt(oldPassword);
        String newPasswordDecrypt = kantbootRsaService.decrypt(newPassword);
        changePassword(oldPasswordDecrypt, newPasswordDecrypt);
    }

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Override
    public SysUserOfSelfVO initSelfInfo(InitSelfInfoDTO initSelfInfoDTO) {
        SysUserOfSelfVO self = getSelf();
        Long selfId = self.getId();
        SysUserOfSelfVO selfVO = BeanUtil.copyProperties(initSelfInfoDTO, SysUserOfSelfVO.class);
        selfVO.setId(selfId);
        selfVO.setIsInit(true);
        selfVO.setDirectCode(self.getDirectCode());
        // 查询所有为空的字段，并且不是id的字段，如果self存在这个字段，就把self的值赋给selfVO
        // 先将两个都转为map,然后遍历selfVO的map，如果self的map中有这个字段，就赋值
        Map<String, Object> selfMap = BeanUtil.beanToMap(self);
        Map<String, Object> selfVOMap = BeanUtil.beanToMap(selfVO);
        // 获取selfMap的key
        selfMap.keySet().forEach(key -> {
            if(!"id".equals(key) && selfVOMap.get(key)==null){
                selfVOMap.put(key, selfMap.get(key));
            }
        });
        // 将selfVOMap的值赋给selfVO
        BeanUtil.fillBeanWithMap(selfVOMap, selfVO, true);

        // 如果有邀请码
        if(initSelfInfoDTO.getInviteCode()!=null){
            // 查询邀请码是否存在
            SysUser byDirectCode = userRepository.findByDirectCode(initSelfInfoDTO.getInviteCode());
            // 如果byDirectCode为空，就不处理
            if(byDirectCode!=null){
                selfVO.setInviteUserId(byDirectCode.getId());
            }
        }

        // 添加用户角色
        // 如果是学生，就添加学生角色
        if("student".equals(initSelfInfoDTO.getRoleCode())){
            sysUserRoleService.addUserRole(selfId, "student");
        } else if ("teacher".equals(initSelfInfoDTO.getRoleCode())) {
            sysUserRoleService.addUserRole(selfId, "teacher");
        }

        return userVOOfSelfShowRepository.save(selfVO);
    }

    @Override
    public SysUserOfSelfInfoVO getSelfOrderInfo() {
        SysUserOfSelfInfoVO sysUserOfSelfInfoVO = new SysUserOfSelfInfoVO();
//        Integer selfOrderInfo = orderRepository.countStatus(getSelfId(), BusWaterGoodsOrder.ORDER_STATUS_CODE_NOT_PROVIDED);
//        Integer selfOrderInfo = orderRepository.countStatus(getSelfId(), BusWaterGoodsOrder.ORDER_STATUS_CODE_IN_DELIVERY);
//        Integer selfOrderInfo = orderRepository.countStatus(getSelfId(), BusWaterGoodsOrder.ORDER_STATUS_CODE_PROVIDED);
//        selfOrderInfo.setInDeliverStatusCount(busWaterGoodsOrderByStatu2);
//        selfOrderInfo.setProvidedGoodsStatusCount(busWaterGoodsOrderByStatu3);
//        selfOrderInfo.setInDeliverStatusCount(busWaterGoodsOrderByStatu1);

        return sysUserOfSelfInfoVO;
    }

    @Override
    public void setUsernameAndPassword(Long id, String username, String password) {
        Long idByUsername = userRepository.findIdByUsername(username);
        if(idByUsername!=null && !idByUsername.equals(id)){
            // 如果用户名已经存在，抛出用户名已存在异常
            throw SystemUserException.USERNAME_EXIST;
        }

        userRepository.findById(id).ifPresent(user -> {
            user.setUsername(username);
            user.setPassword(kantbootPassword.encode(password));
            userRepository.save(user);
        });
    }
}
